package com.yonyou.pmclouds.workquality.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.mapper.WorkqualityMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class WorkqualityMultiInsertCheckProcessor implements MultiProcessor<WorkqualityVO> {

    private WorkqualityMapper mapper;

    public WorkqualityMultiInsertCheckProcessor(WorkqualityMapper mapper) {
        this.mapper = mapper;
    }
    @Override
    public void process(WorkqualityVO[] vos, WorkqualityVO[] origs) throws BusinessException {
        if (vos == null || vos.length == 0 || vos[0] == null) return;
        String pkTenant = vos[0].getPkTenant();
        List<String> names = new ArrayList<>();
        for (WorkqualityVO vo : vos) {
            if (vo != null) {
                names.add(vo.getCheckname());
            }
        }
        if(names == null || names.size() == 0) return;
        String[] conflictNames = mapper.checkNames(pkTenant, SqlUtil.getSqlIn(names.toArray(new String[0]))); //冲突的名字
        if (!ArrayUtils.isEmpty(conflictNames)) {  //存在冲突
            StringBuffer errorMsg = new StringBuffer();
            //错误信息中添加冲突的名字
            if (!ArrayUtils.isEmpty(conflictNames)) {
                for (int i = 0; i < conflictNames.length; i++) {
                    if (!StringUtils.isEmpty(conflictNames[i])) {
                        errorMsg.append(conflictNames[i]);
                        errorMsg.append(i == conflictNames.length - 1 ? "。" : "，");
                    }
                }
            }
            throw new BusinessException(errorMsg.toString(), "名字冲突");
        }
    }
}
